package com.vm.fragment;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.vm.activity.CategoryActivity;
import com.vm.activity.DetailActivity;
import com.vm.activity.NecessaryAppActivity;
import com.vm.activity.NecessaryGameActivity;
import com.vm.activity.PresentActivity;
import com.vm.activity.TopActivity;
import com.vm.activity.UserInfoActivity;
import com.vm.adapter.FoundAdapter;
import com.vm.adapter.FoundPresentAdapter;
import com.vm.commons.CurrentUser;
import com.vm.commons.StringUtil;
import com.vm.commons.VMConst;
import com.vm.model.ActiveSoft;
import com.vm.myview.ViewUtils;
import com.vm.utils.MyVolley;
import com.vm.utils.SingleRequestQueue;
import com.wwtscapp.apk.R;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

@SuppressLint("InflateParams")
public class FoundFragment extends BaseFragment {
	protected static final String TAG = "FoundActivity";

	ScrollView mScrollView;
	boolean canRequest = false;
	int pageNow = 1;
	private View view;
	private RequestQueue mQueue;
	Button btn_recommended;
	Button btn_hot_game;
	Button btn_latest_application;
	Button btn_topical_application;
	Button btn_latest_game;
	Button btn_recommend_online_game;
	Button rbtn_category;
	Button btn_ranking;
	Button btn_app;
	Button btn_game;
	ViewUtils viewUtils;
	RelativeLayout rl_present;
	TextView tv_time;
//	ImageView iv_viwepager6;
	String serverTime = null;

	String start = null;
	/** 标志位，标志已经初始化完成 */
	private boolean isPrepared;
	/** 是否已被加载过一次，第二次就不再去请求数据了 */
	private boolean mHasLoadedOnce;
	Gson gson = new Gson();

	TextView tv_wonderful_game;
	GridView gv_wonderful_game;
	TextView tv_tourist_traffic;
	LinearLayout found_ll_3;
	TextView tv_financial_payment;
	GridView gv_FP;
	TextView tv_find_job;
	LinearLayout found_ll_4;
	TextView tv_entertainment_applications;
	GridView gv_ETM;
	TextView tv_lastest;
	GridView gv_lastest;
	Message msg;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		Log.i("FoundFragment", "onCreateView");

		if (view == null) {
			view = inflater.inflate(R.layout.found, null);
		} else {
			// 缓存的rootView需要判断是否已经被加过parent
			// 如果有parent需要从parent删除
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null) {
				parent.removeView(view);
			}
		}

		isPrepared = true;
		lazyLoad();

		view.setVisibility(View.INVISIBLE);

		// = inflater.inflate(R.layout.found, null);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		Log.i("FoundFragment", "onActivityCreated");

	}

	OnItemClickListener gd_listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			Intent intent = new Intent(getActivity(), DetailActivity.class);
			TextView textView = (TextView) view.findViewById(R.id.tv_softName);
			String softId = textView.getTag().toString();
			intent.putExtra("softId", softId);
			startActivityForResult(intent, 10);

		}
	};

	/**
	 * 初始化登录
	 */
	public static void login(ImageView iv_logo) {

		iv_logo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(),
						UserInfoActivity.class);
				v.getContext().startActivity(intent);
			}
		});
	}

	/**
	 * 下载按钮监听
	 */
	public OnClickListener downClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			Button btn_soft_download = (Button) v;

			if (btn_soft_download.getText().toString().equals("已安装")) {
				// 不做任何操作
			} else if (btn_soft_download.getText().toString().toString()
					.equals("安装")) {
				// 执行安装
				Toast toast3 = Toast.makeText(getActivity(), "正在安装", 500);
				toast3.setGravity(Gravity.CENTER, 0, 0);
				toast3.show();
				btn_soft_download.setText("正在安装");

				File apkfile = new File(
						StringUtil.getSdApkUrl(btn_soft_download.getTag()
								.toString()));
				if (!apkfile.exists()) {
					return;
				}
				Intent i = new Intent(Intent.ACTION_VIEW);
				i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
						"application/vnd.android.package-archive");
				startActivity(i);

			} else {

				// 下载APK

			}

		}
	};

	@Override
	protected void lazyLoad() {

		Log.i("FoundFragment", "lazyLoad");
		Log.i("lazyLoad", "isPrepared=" + isPrepared + ",isVisible="
				+ isVisible + ",mHasLoadedOnce=" + mHasLoadedOnce);
		// TODO Auto-generated method stub
		if (!isPrepared || !isVisible || mHasLoadedOnce) {
			return;
		}
		Log.i("FoundFragment", "lazyLoad--AsyncTask");
		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// 显示加载进度对话框
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try {
					Thread.sleep(1000);
					// 在这里添加调用接口获取数据的代码
					// doSomething()
					initData();
					// doSomething()
				} catch (Exception e) {
					e.printStackTrace();
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean isSuccess) {
				if (isSuccess) {
					// 加载成功

					mHasLoadedOnce = true;
				} else {
					// 加载失败
				}

			}
		}.execute();

	}

	public void initBtn() {
		// iv_viwepager6 = (ImageView) view.findViewById(R.id.iv_viwepager6);
		// iv_viwepager6.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// Intent intent = new Intent(getActivity(), PresentActivity.class);
		// startActivity(intent);
		// }
		// });
		rbtn_category = (Button) view.findViewById(R.id.rbtn_category);
		btn_ranking = (Button) view.findViewById(R.id.btn_ranking);
		btn_app = (Button) view.findViewById(R.id.btn_app);
		btn_game = (Button) view.findViewById(R.id.btn_game);
		rbtn_category.setOnClickListener(btn_clicklistener);
		btn_ranking.setOnClickListener(btn_clicklistener);
		btn_app.setOnClickListener(btn_clicklistener);
		btn_game.setOnClickListener(btn_clicklistener);

		mScrollView = (ScrollView) view.findViewById(R.id.scrollView2);
		mScrollView.setOnTouchListener(new TouchListenerImpl());

		tv_wonderful_game = (TextView) view
				.findViewById(R.id.tv_wonderful_game);
		gv_wonderful_game = (GridView) view.findViewById(R.id.gv_WG);

		tv_tourist_traffic = (TextView) view
				.findViewById(R.id.tv_tourist_traffic);
		found_ll_3 = (LinearLayout) view.findViewById(R.id.found_ll_3);

		tv_financial_payment = (TextView) view
				.findViewById(R.id.tv_financial_payment);
		gv_FP = (GridView) view.findViewById(R.id.gv_FP);
		tv_find_job = (TextView) view.findViewById(R.id.tv_find_job);
		found_ll_4 = (LinearLayout) view.findViewById(R.id.found_ll_4);
		tv_entertainment_applications = (TextView) view
				.findViewById(R.id.tv_entertainment_applications);
		gv_ETM = (GridView) view.findViewById(R.id.gv_ETM);
		tv_lastest = (TextView) view.findViewById(R.id.tv_lastest);
		gv_lastest = (GridView) view.findViewById(R.id.gv_lastest);

	}

	public OnClickListener btn_clicklistener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent;
			switch (v.getId()) {
			case R.id.rbtn_category:
				intent = new Intent(getActivity(), CategoryActivity.class);
				startActivity(intent);
				break;
			case R.id.btn_ranking:
				intent = new Intent(getActivity(), TopActivity.class);
				startActivity(intent);
				break;
			case R.id.btn_app:
				intent = new Intent(getActivity(), NecessaryAppActivity.class);
				startActivity(intent);
				break;
			case R.id.btn_game:
				intent = new Intent(getActivity(), NecessaryGameActivity.class);
				startActivity(intent);
				break;
			default:
				break;
			}
		}

	};

	public void initData() {

		getServerTime();
		initBtn();

		rl_present = (RelativeLayout) view.findViewById(R.id.rl_present);
		rl_present.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(), PresentActivity.class);
				startActivity(intent);
			}
		});
		mQueue = SingleRequestQueue.getRequestQueue(getActivity());
		viewUtils = new ViewUtils(getActivity());

		// initData4();

	}

	/**
	 * 加载数据
	 */
	public void getFound() {
		String url = VMConst.REQUEST_URL
				+ VMConst.ActiveType.getFound.toString() + "?activeTime="
				+ start;
		if (CurrentUser.USERID != null) {
			url += "&userId=" + CurrentUser.USERID;
		}

		msg = new Message();
		msg.what = 10;
		mainHandler.sendMessage(msg);
		JsonArrayRequest json_present = new JsonArrayRequest(url,
				new Listener<JSONArray>() {

					@Override
					public void onResponse(JSONArray arg0) {
						// TODO Auto-generated method stub
						List<ActiveSoft> list_prestent = new ArrayList<ActiveSoft>();
						List<ActiveSoft> list_lcu = new ArrayList<ActiveSoft>();
						JSONObject jsonObject;
						ActiveSoft activeSoft;
						if (arg0.length() == 14) {
							canRequest = true;
						}

						Gson gson = new Gson();
						for (int i = 0; i < 14; i++) {
							try {
								jsonObject = arg0.getJSONObject(i);
								activeSoft = gson.fromJson(
										jsonObject.toString(), ActiveSoft.class);

								if (i < 4) {
									list_prestent.add(activeSoft);
								} else if (i >= 4 && i < 6) {

									LinearLayout found_ll_1 = (LinearLayout) view
											.findViewById(R.id.found_ll_1);

									// LinearLayout linearLayout =
									// dyAddView(i,
									// activeSoft);
									found_ll_1.addView(viewUtils.dyAddView(i,
											activeSoft, 1));

								} else if (i >= 6 && i < 10) {
									list_lcu.add(activeSoft);

								} else if (i >= 10) {

									LinearLayout found_ll_1 = (LinearLayout) view
											.findViewById(R.id.found_ll_2);

									found_ll_1.addView(viewUtils.dyAddView(i,
											activeSoft, 1));

								}

							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						FoundPresentAdapter adapter = new FoundPresentAdapter(
								getActivity(), list_prestent);
						GridView gridView = (GridView) view
								.findViewById(R.id.gv_present);
						gridView.setFocusable(false);
						gridView.setOnItemClickListener(gd_listener);
						gridView.setAdapter(adapter);

						FoundAdapter adapter2 = new FoundAdapter(getActivity(),
								list_lcu);
						GridView gridView2 = (GridView) view
								.findViewById(R.id.gv_LCU);
						gridView2.setFocusable(false);
						gridView2.setOnItemClickListener(gd_listener);
						gridView2.setAdapter(adapter2);

						msg = new Message();
						msg.what = 20;
						mainHandler.sendMessage(msg);
					}

				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// Log.e(TAG, error.getMessage(), error);
						msg = new Message();
						msg.what = 20;
						mainHandler.sendMessage(msg);
					}
				});

		mQueue.add(json_present);
	}

	/**
	 * 获取服务器时间
	 */
	public void getServerTime() {
		mQueue = MyVolley.getRequestQueue();
		String url = VMConst.REQUEST_URL + "getTime";
		StringRequest stringRequest = new StringRequest(url,
				new Listener<String>() {
					@Override
					public void onResponse(String arg0) {
						// TODO Auto-generated method stub
						serverTime = arg0.toString().replace("\"", "");
						serverTime = serverTime.substring(11);
						// System.out.println(nowTime);

						// String stime = null;
						int nowHour = Integer.parseInt(serverTime.substring(0,
								2));

						if (nowHour < 8) {
							nowHour = 0;
							start = "0";
						} else {
							if (nowHour % 2 != 0) {
								start = Integer.toString(nowHour - 1);
							} else {
								start = Integer.toString(nowHour);
							}
						}

						tv_time = (TextView) view.findViewById(R.id.tv_time);
						tv_time.setText(start + "点场");
						// nav_radiogroup.set
						// getPrestent();
						// initData2();

						getFound();
					}

				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						// TODO Auto-generated method stub

					}
				});

		mQueue.add(stringRequest);
	}

	FoundAdapter adapter6;

	List<ActiveSoft> list_latest = new ArrayList<ActiveSoft>();

	/**
	 * 滑动监听
	 * 
	 * @author Administrator
	 * 
	 */
	private class TouchListenerImpl implements OnTouchListener {
		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			switch (motionEvent.getAction()) {
			case MotionEvent.ACTION_DOWN:

				break;
			case MotionEvent.ACTION_MOVE:
				int scrollY = view.getScrollY();
				int height = view.getHeight();
				int scrollViewMeasuredHeight = mScrollView.getChildAt(0)
						.getMeasuredHeight();
				if (scrollY == 0) {
					System.out.println("滑动到了顶端view.getScrollY()=" + scrollY);
				}
				if ((scrollY + height) == scrollViewMeasuredHeight) {

					if (canRequest) {
						msg = new Message();
						msg.what = 10;
						mainHandler.sendMessage(msg);
						canRequest = false;
						System.out.print("canRequest:" + canRequest);
						pageNow++;
						System.out.print("pageNow:" + pageNow);
						String url = VMConst.REQUEST_URL
								+ VMConst.ActiveType.getFound.toString()
								+ "?pageNow=" + pageNow;
						JsonArrayRequest searchArrayRequest = new JsonArrayRequest(
								url, new Listener<JSONArray>() {
									@Override
									public void onResponse(JSONArray arg0) {
										Log.i(TAG, "json长度:" + arg0.length());

										List<ActiveSoft> list_WG = new ArrayList<ActiveSoft>();
										List<ActiveSoft> list_FP = new ArrayList<ActiveSoft>();
										List<ActiveSoft> list_ETM = new ArrayList<ActiveSoft>();

										JSONObject jsonObject = null;
										ActiveSoft activeSoft = null;
										// 第二页
										if (pageNow == 2) {
											for (int i = 0; i < 10; i++) {
												try {
													jsonObject = arg0
															.getJSONObject(i);
													if (jsonObject != null) {

														if (i < 6) {
															list_WG.add(gson.fromJson(
																	jsonObject
																			.toString(),
																	ActiveSoft.class));
														} else if (i >= 6) {
															try {
																tv_tourist_traffic
																		.setVisibility(View.VISIBLE);
																found_ll_3
																		.setVisibility(View.VISIBLE);
																jsonObject = arg0
																		.getJSONObject(i);
																activeSoft = gson
																		.fromJson(
																				jsonObject
																						.toString(),
																				ActiveSoft.class);

																found_ll_3
																		.addView(viewUtils
																				.dyAddView(
																						i,
																						activeSoft,
																						1));

															} catch (JSONException e) {
																// TODO
																// Auto-generated
																// catch block
																e.printStackTrace();
															}
														}
													}
												} catch (JSONException e) {
													// TODO Auto-generated catch
													// block
													e.printStackTrace();
												}

											}

											FoundAdapter adapter3 = new FoundAdapter(
													getActivity(), list_WG);

											tv_wonderful_game
													.setVisibility(View.VISIBLE);
											gv_wonderful_game
													.setVisibility(View.VISIBLE);
											gv_wonderful_game
													.setFocusable(false);
											gv_wonderful_game
													.setOnItemClickListener(gd_listener);
											gv_wonderful_game
													.setAdapter(adapter3);

										}
										// 第三页
										else if (pageNow == 3) {
											for (int i = 0; i < 10; i++) {
												try {
													jsonObject = arg0
															.getJSONObject(i);
													if (jsonObject != null) {
														if (i < 4) {
															list_FP.add(gson.fromJson(
																	jsonObject
																			.toString(),
																	ActiveSoft.class));
														} else if (i >= 4
																&& i < 6) {
															try {
																tv_find_job
																		.setVisibility(View.VISIBLE);
																found_ll_4
																		.setVisibility(View.VISIBLE);
																jsonObject = arg0
																		.getJSONObject(i);
																activeSoft = gson
																		.fromJson(
																				jsonObject
																						.toString(),
																				ActiveSoft.class);

																found_ll_4
																		.addView(viewUtils
																				.dyAddView(
																						i,
																						activeSoft,
																						1));

															} catch (JSONException e) {
																// TODO
																// Auto-generated
																// catch block
																e.printStackTrace();
															}
														} else if (i >= 6) {
															list_ETM.add(gson.fromJson(
																	jsonObject
																			.toString(),
																	ActiveSoft.class));
														}
													}
												} catch (JSONException e) {
													// TODO Auto-generated catch
													// block
													e.printStackTrace();
												}

											}

											FoundAdapter adapter4 = new FoundAdapter(
													getActivity(), list_FP);

											tv_financial_payment
													.setVisibility(View.VISIBLE);
											gv_FP.setVisibility(View.VISIBLE);
											gv_FP.setFocusable(false);
											gv_FP.setOnItemClickListener(gd_listener);
											gv_FP.setAdapter(adapter4);

											FoundAdapter adapter5 = new FoundAdapter(
													getActivity(), list_ETM);

											tv_entertainment_applications
													.setVisibility(View.VISIBLE);
											gv_ETM.setVisibility(View.VISIBLE);
											gv_ETM.setFocusable(false);
											gv_ETM.setOnItemClickListener(gd_listener);
											gv_ETM.setAdapter(adapter5);
										} else if (pageNow > 3) {

											try {
												Type type = new TypeToken<List<ActiveSoft>>() {
												}.getType();
												List<ActiveSoft> templist = new ArrayList<ActiveSoft>();

												templist = gson.fromJson(
														arg0.toString(), type);
												list_latest.addAll(templist);

												if (adapter6 != null) {

													adapter6 = new FoundAdapter(
															getActivity(),
															list_latest);

													gv_lastest
															.setAdapter(adapter6);

													adapter6.notifyDataSetChanged();
													// gv_lastest
													// adapter6.
												} else {
													adapter6 = new FoundAdapter(
															getActivity(),
															list_latest);

													tv_lastest
															.setVisibility(View.VISIBLE);
													gv_lastest
															.setVisibility(View.VISIBLE);
													gv_lastest
															.setFocusable(false);
													gv_lastest
															.setOnItemClickListener(gd_listener);
													gv_lastest
															.setAdapter(adapter6);

												}

											} catch (JsonSyntaxException e) {
												// TODO Auto-generated catch
												// block
												Log.e("加载数据错误", e.getMessage());
											}
											// list_latest.notifyAll();
										}

										canRequest = true;
										msg = new Message();
										msg.what = 20;
										mainHandler.sendMessage(msg);

									}

								}, new Response.ErrorListener() {
									@Override
									public void onErrorResponse(
											VolleyError error) {
										// Log.e(TAG, error.getMessage(),
										// error);
										msg = new Message();
										msg.what = 20;
										mainHandler.sendMessage(msg);
									}
								});

						mQueue.add(searchArrayRequest);

						// System.out.println("滑动到了底部 scrollY=" + scrollY);
						// System.out.println("滑动到了底部 height=" + height);
						// System.out.println("滑动到了底部 scrollViewMeasuredHeight="
						// + scrollViewMeasuredHeight);
					}

				}
				break;

			default:
				break;
			}
			return false;
		}
	};

	@SuppressLint("HandlerLeak")
	private Handler mainHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 10:
				UIHelper.showDialogForLoading(getActivity(), "正在加载...", true);
				break;
			case 20:
				UIHelper.hideDialogForLoading();
				view.setVisibility(View.VISIBLE);
				break;
			}
		}
	};

}
